//
//  NetWorkerOperation.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/1.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit
typealias SuccessCallback = (_ source : Dictionary<String,Any>)->Void
typealias FailCallBack = (_ errorCode : Int)->Void

class NetWorkerOperation: Operation,URLSessionDataDelegate {
    private var task : URLSessionDataTask?
    private var success : SuccessCallback?
    private var fail : FailCallBack?
    private var sourceData : Data?
    class func create(request : URLRequest,completion : @escaping SuccessCallback,failed : @escaping FailCallBack)->NetWorkerOperation {
        let worker = NetWorkerOperation.init()
        let session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: worker, delegateQueue: nil)
        worker.task = session.dataTask(with: request)
        worker.success = completion
        worker.fail = failed
        worker.sourceData = Data.init()
        return worker;
    }
    
    class func createUpload(request : URLRequest,data : Data?,completion : @escaping SuccessCallback,failed : @escaping FailCallBack)->NetWorkerOperation{
        let worker = NetWorkerOperation.init()
        let session = URLSession.init(configuration: URLSessionConfiguration.default, delegate: worker, delegateQueue: nil)
        worker.task = session.uploadTask(with: request, from: data, completionHandler: { (dt, response, error) in
            if dt != nil {
                do {
                    let json = try JSONSerialization.jsonObject(with: dt!, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary<String,Any>
                    //print(json)
                    completion(json)
                } catch {
                    //print(error)
                    failed(-3)
                }
            }
        })
//        worker.success = completion
//        worker.fail = failed
//        worker.sourceData = Data.init()
        return worker;
    }
    
    override func main() {
        task?.resume()
    }
    
    //接受到数据
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        sourceData?.append(data)
    }
    
    func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
        
    }
    //收到https质询
//    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//        
//    }
    
    
    
    //完成
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        guard error == nil else {
            fail?(-1)
            session.invalidateAndCancel()
            success = nil
            fail = nil
            return
        }
        guard sourceData != nil else {
            session.finishTasksAndInvalidate()
            fail?(-2)
            success = nil
            fail = nil
            return
        }
        do {
            let json = try JSONSerialization.jsonObject(with: sourceData!, options: JSONSerialization.ReadingOptions.allowFragments) as! Dictionary<String,Any>
            //print(json)
            success!(json)
        } catch {
            //print(error)
            fail?(-3)
        }
        session.finishTasksAndInvalidate()
        success = nil
        fail = nil
    }
    
    deinit {
        task = nil
        sourceData = nil
        print("被释放了")
    }
}
